﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DynamicToolkit.Tests.Helpers
{
    class XpathAssert
    {
        private readonly static Lazy<XmlDocument> doc = new Lazy<XmlDocument>(() => CreateDocument());

        private static XmlDocument CreateDocument()
        {
            var d = new XmlDocument();
            d.LoadXml("<a/>");
            return d;
        }

        public static void IsValidUnwrappedPredicate(string predicate)
        {
            if (string.IsNullOrWhiteSpace(predicate))
            {
                Assert.Fail(string.Format("Invalid xpath: '{0}'", predicate));
            }

            string wrappedPredicate = string.Format("[{0}]", predicate);
            IsValidPredicate(wrappedPredicate);
        }

        public static void IsValidPredicate(string predicate)
        {
            if (string.IsNullOrWhiteSpace(predicate))
            {
                Assert.Fail(string.Format("Invalid xpath: '{0}'", predicate));
            }

            try
            {
                string xpath = string.Format("/*{0}", predicate);
                doc.Value.SelectSingleNode(xpath);
            }
            catch(Exception ex)
            {
                Assert.Fail("Invalid predicate: '{0}'.  Error: {1}", predicate, ex.Message);
            }
        }

        public static void IsValidXpath(string xpath)
        {
            try
            {
                doc.Value.SelectSingleNode(xpath);
            }
            catch
            {
                Assert.Fail("Invalid predicate: '{0}'", xpath);
            }
        }
    }
}
